package com.gf.controller.shop;


import com.alibaba.fastjson.JSONObject;
import com.gf.bean.Shop;
import com.gf.service.impl.ShopServiceImpl;
import com.gf.utils.Const;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.io.*;

import java.util.List;


/*
* 处理注册店铺请求的servlet
* */


@WebServlet(name = "RegistersmenuServlet",urlPatterns = "/regshop")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    static ShopServiceImpl shopimpl = null;
    static {
        shopimpl=new ShopServiceImpl();


    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        JSONObject obj = new JSONObject();
        Shop shop1=null;
        String shop_name=null;
        String shop_address=null;
        String shop_value=null;
        String suffix=null;
        PrintWriter out= response.getWriter();
        //判断请求是否为multipart请求
        if(!ServletFileUpload.isMultipartContent(request)){
            throw new RuntimeException("当前请求不支持文件上传");
        }
        try {
            //创建一个FileItem工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //创建文件上传核心组件
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            //解析请求，获取到所有的item
            List<FileItem> items = servletFileUpload.parseRequest(request);
            //遍历items
            for(FileItem item : items){
                if(item.isFormField()){  //若item为普通表单项
                    String fieldName = item.getFieldName();  //获取表单项名称
                    String fieldValue = item.getString();  //获取表单项的值
                    fieldValue= new String(fieldValue.getBytes("ISO-8859-1"),"utf-8");
                    // new String(s.getBytes("ISO-8859-1"),"utf-8"); 转码
                    switch (fieldName) {
                        case "shop_name":
                            shop_name = fieldValue;
                            shop1 = shopimpl.selectshopname(shop_name);
                            if (shop1!=null){
                                response.setStatus(300);
                                obj.put("status", 300);
                                obj.put("message", Const.HADSHOPNAME);
                            }
                            break;
                        case "shop_address":
                            shop_address=fieldValue;
                            break;
                        case "shop_value":
                            shop_value=fieldValue;
                            break;
                    }
                    System.out.println(fieldName+"="+fieldValue);
                }else{  //若item为文件表单项
                    //获取上传文件原始名称
                    String fileName = item.getName();
                    suffix="."+fileName.substring(fileName.lastIndexOf(".") + 1);
                    //获取输入流，其中有上传 文件的内容
                    InputStream is = item.getInputStream();
                    //获取文件保存在服务器的路径
                    String path = this.getServletContext().getRealPath("/images/shop");
                    //创建目标文件，将用来保存上传文件
                    File file = new File(path, shop_name+suffix);
                    //将输入流中的数据写入到输出流中
                    OutputStream os = new FileOutputStream(file);
                    //将输入流中的数据写入输出流中
                    int len = -1;
                    byte[] buf = new byte[1024];
                    while((len = is.read(buf)) != -1){
                        os.write(buf, 0, len);
                    }

                    os.close();
                    is.close();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (shop1==null){
            Shop shop = new Shop();
            shop.setShop_name(shop_name);//设置店铺名字
            shop.setShop_address(shop_address);//设置店铺地址
            shop.setShop_value(shop_value);//设置店铺简介
            shop.setShop_img_url("images/shop/"+shop_name+suffix);//存放上传店铺图片的相对路径
            shop.setScore(9.0f);//默认9.0评分
            shopimpl.insert(shop);
            response.setStatus(200);
            obj.put("status", 200);
            obj.put("message", "店铺插入成功");


        }
        out.println(JSONObject.toJSON(obj));
        out.flush();
        out.close();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        }
}
